﻿@model GolfLeague.EditModels.ScoresEditModel

<script type="text/javascript">
    $(document).ready(function () {
        $('#SavingDialog').dialog({
            autoOpen: false,
            closeOnEscape: false,
            draggable: false,
            model: true,
            resizable: false
        });
        $('#CalculatingDialog').dialog({
            autoOpen: false,
            closeOnEscape: false,
            draggable: false,
            model: true,
            resizable: false
        });
        $('input:button').button();
        $('input:submit').button();
        $('#SaveComplete').hide();
        $('#CalculationComplete').hide();
    });

    $(function () {
        $('#ScheduleDropDown').change(function () {
            var scheduleID = $(this).val();
            var options = '';

            if (scheduleID != '') {
                $.ajax({
                    url: '/Score/RoundDropdown',
                    type: 'GET',
                    dataType: 'json',
                    //data: '{ scheduleID : "' + scheduleID + '"}',
                    data: 'scheduleID=' + scheduleID,
                    contentType: 'application/json; charset=utf-8',
                    error: function (xhr, status, error) {
                        alert(xhr + '\n' + status + '\n' + error);
                    },
                    success: function (data) {
                        $.each(data.roundsDropDownList, function (i, value) {
                            options += '<option value="' + value.RoundID + '">' + value.RoundDate + '</option>';
                        });
                        $('#RoundDropDown').html(options);
                        var roundID = $('#RoundDropDown').val();
                        RenderMatches(roundID);
                    }
                });
            }
        });
    });

    $(function () {
        $('#RoundDropDown').change(function () {
            var roundID = $(this).val();
            RenderMatches(roundID);
        });
    });

    function RenderMatches(roundID) {
        if (roundID != '') {
            $.ajax({
                url: '/Score/Matches?roundID=' + roundID,
                type: 'GET',
                dataType: 'html',
                success: function (data) {
                    $('#Matches').html(data);
                    $('input:button').button();
                    $('#Scorecards').html('<fieldset><legend>Scorecard</legend><h4>No scorecard exists for this match.</h4></fieldset>');
                }
            });
        }
    }

    function GetMatchScorecard(btnClicked) {
        var matchID = $(btnClicked).attr('id');
        matchID = matchID.replace('edit-', '');

        if (matchID != '') {
            $.ajax({
                url: '/Score/Scorecard?id=' + matchID,
                type: 'GET',
                dataType: 'html',
                success: function (data) {
                    $('#Scorecards').html(data);
                    $('input:button').button();
                    $('input:submit').button();
                }
            });
        }
    }

    function CalculatePoints(btnClicked) {
        var roundID = $(btnClicked).attr('id');
        roundID = roundID.replace('calculate-points-', '');

        if (roundID != '') {
            $('#CalculatingDialog').dialog('open');
            $.ajax({
                url: '/Score/CalculatePoints/' + roundID,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                complete: function () {
                    $('#CalculatingDialog').dialog('close');
                    $('#CalculationComplete').hide('slide', {}, 10000);
                },
                success: function () {
                    $('#CalculationComplete').effect('highlight', {}, 3000);
                }
            });
        }
    }

    function SaveScorecard(btnClicked) {
        $('#SavingDialog').dialog('open');

        var model = GetModelObject();
        $.ajax({
            url: '/Score/Scorecard',
            type: 'POST',
            data: JSON.stringify(model),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            complete: function () {
                $('#SavingDialog').dialog('close');
                $('#SaveComplete').hide('slide', {}, 10000);
            },
            success: function () {
                $('#SaveComplete').effect('highlight', {}, 3000);
            }
        });

    }

    function GetModelObject() {
        var model;

        var matchID = $('#MatchID').val();
        var PlayerCount = $('#PlayerScoresCount').val();

        var PlayerScoresList = new Array();
        for (var i = 0; i < PlayerCount; i++) {
            PlayerScoresList[i] = GetPlayerScorecardObject(i);
        }

        return { PlayerScores: PlayerScoresList, MatchID: matchID };
    }

    function GetPlayerScorecardObject(playerNum) {
        //var individualMatchID = $('#PlayerScores_' + playerNum + '__IndividualMatchID').val();
        var matchHandicap = $('#handicap_' + playerNum).text();
        var playerID = $('#PlayerScores_' + playerNum + '__PlayerID').val();
        var playerMatch = GetPlayerMatchObject(playerNum);

        var Scores = new Array();
        for (var j = 0; j < 9; j++) {
            Scores[j] = GetScoreObject(playerNum, j);
        }

        return { PlayerStrokes: Scores, PlayerID: playerID, PlayerMatch: playerMatch, MatchHandicap: matchHandicap }; //, IndividualMatchID: individualMatchID };
    }

    function GetPlayerMatchObject(playerNum) {
        var playerMatchID = parseInt($('#PlayerScores_' + playerNum + '__PlayerMatch_PlayerMatchID').val());
        var handicap = parseInt($('#handicap_' + playerNum).text());
        var handicapID = parseInt($('#PlayerScores_' + playerNum + '__PlayerMatch_HandicapID').val());
        var opponentID = parseInt($('#PlayerScores_' + playerNum + '__PlayerMatch_OpponentID').val());
        var grossScore = parseInt($('#stroke_Total_' + playerNum).text());
        var netScore = grossScore - handicap;
        var points = parseInt($('#points_' + playerNum).text());
        var playerID = parseInt($('#PlayerScores_' + playerNum + '__PlayerMatch_PlayerID').val());
        var matchID = parseInt($('#MatchID').val());

        return { PlayerMatchID: playerMatchID, GrossScore: grossScore, NetScore: netScore, Points: points, PlayerID: playerID, MatchID: matchID, OpponentID: opponentID, HandicapID: handicapID };
    }

    function GetScoreObject(playerNum, scoreNum) {
        var holeID = $('#PlayerScores_' + playerNum + '__PlayerStrokes_' + scoreNum + '__HoleID').val();
        var strokes = $('#PlayerScores_' + playerNum + '__PlayerStrokes_' + scoreNum + '__Strokes').val()

        return { HoleID: holeID, Strokes: strokes };
    }

    function SumPlayerStrokes(playerNum) {
        var strokesTotal = 0;
        var x = 0;

        for (var j = 0; j < 9; j++) {
            strokesTotal += parseInt($('#PlayerScores_' + playerNum + '__PlayerStrokes_' + j + '__Strokes').val());
        }
        $('#stroke_Total_' + playerNum).html(strokesTotal);
        var handicap = $('#handicap_' + playerNum).text();
        $('#net_Stroke_Total_' + playerNum).html(strokesTotal - handicap);
    }

    function PlayerCheckBox_Click(checkBox) {
        var playerID = checkBox.id;
        playerID = playerID.replace('edit_Points_', '')
        var pointsInput = document.getElementById('PlayerScores_' + playerID + '__PlayerMatch_Points');
        pointsInput.readOnly = !checkBox.checked;
    }

    function TeamCheckBox_Click(checkBox) {
        var teamID = checkBox.id;
        teamID = teamID.replace('edit_Team_Points_', '')
        var pointsInput = document.getElementById('TeamMatches_' + teamID);
        pointsInput.readOnly = !checkBox.checked;
    }

</script>
@{
    ViewBag.Title = "Scores";
}

<h2>Scores</h2>

@Html.DropDownList("ScheduleDropDown", new SelectList(Model.Schedules, "ScheduleID", "ScheduleName", Model.ScheduleID))
@Html.DropDownList("RoundDropDown", new SelectList(Model.RoundsDropDownList, "RoundID", "RoundDate", Model.RoundID))
<br /><br />
<div style="height:1em" >
    <div id="CalculatingDialog" style="text-align:center">Calculating...<br /><img src="/Content/images/loading_animated.gif" alt="Please wait." /></div>
    <div id="CalculationComplete">Points have been calculated.</div>
</div>
<div id="Matches">@Html.Partial("_Matches", Model.Round)</div>
<div style="height:1em" >
    <div id="SavingDialog" style="text-align:center">Saving...<br /><img src="/Content/images/loading_animated.gif" alt="Please wait." /></div>
    <div id="SaveComplete">Scorecard was saved.</div>
</div>
<div id="Scorecards">@Html.Partial("_Scorecard", Model.ScoresScorecardEditModel)</div>
<div>
    @Html.ActionLink("Back to Admin Home", "Admin", "Home")
</div>
